<template>
  <!-- 集装箱项目 配置 -->
  <a-form
    :model="form"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
    layout="vertical"
    ref="formRef"
    :rules="rules"
    :disabled="!configData.isEdit"
  >
    <a-form-item label="所属厂商" name="supplierId">
      <a-select
        v-model:value="form.supplierId"
        class="formInput"
        placeholder="请选择"
        @change="changeSupplierType"
        allow-clear
        :loading="formLoading"
      >
        <a-select-option
          v-for="item in supplierList"
          :value="item.supplierId"
          :key="item.supplierId"
        >
          {{ item.supplierShortName }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="所属设备型号" name="typeId">
      <a-select
        v-model:value="form.typeId"
        class="formInput"
        placeholder="请选择"
        :disabled="!form.supplierId || !configData.isEdit"
        allow-clear
        :loading="formLoading"
        @change="changeType"
      >
        <a-select-option
          v-for="item in supplierTypeList"
          :value="item.id"
          :key="item.id"
        >
          {{ item.type }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="集装箱名称" name="linkName">
      <a-input v-model:value="form.linkName" class="formInput" />
    </a-form-item>
    <a-form-item label="设备编号" name="orderNum">
      <a-input v-model:value="form.orderNum" class="formInput" />
    </a-form-item>
    <a-form-item label="集装箱项目资产编码" name="linkAssetCode">
      <a-input v-model:value="form.linkAssetCode" class="formInput" />
    </a-form-item>
    <a-form-item label="是否为主集装箱" name="isMain">
      <a-select class="formSelect" v-model:value="form.isMain">
        <a-select-option :value="1">是</a-select-option>
        <a-select-option :value="0">否</a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="所属集装箱" name="belongId" v-if="!form.isMain">
      <a-select class="formSelect" v-model:value="form.belongId">
        <a-select-option
          v-for="item in energyLinkList"
          :value="item.deviceId"
          :key="item.deviceId"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <!-- 所属变压器 如果是主集装箱就必填 -->
    <a-form-item label="所属变压器" :name="form.isMain ? 'tfId' : ''">
      <a-select
        v-model:value="form.tfId"
        class="formInput"
        placeholder="请选择"
        allow-clear
        :loading="formLoading"
      >
        <a-select-option
          v-for="item in BIAN_YA_QI_LIST"
          :value="item.systemId"
          :key="item.systemId"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <!-- <a-form-item label="支路关口表数据来源" name="branchMeterId">
      <a-select class="formSelect" v-model:value="form.branchMeterId">
        <a-select-option :value="1">是</a-select-option>
        <a-select-option :value="0">否</a-select-option>
      </a-select>
    </a-form-item> -->
    <a-form-item label="唯一标识/设备序列号" name="linkIdx">
      <a-input v-model:value="form.linkIdx" class="formInput" />
    </a-form-item>
    <a-form-item label="集装箱内电池簇数量" name="blockNum">
      <a-input-number
        v-model:value="form.blockNum"
        class="formInput"
        :controls="false"
      />
    </a-form-item>
    <a-form-item label="PACK数量/电池簇" name="packNum">
      <a-input-number
        v-model:value="form.packNum"
        class="formInput"
        :controls="false"
      />
    </a-form-item>
    <a-form-item label="电芯数量/PACK" name="cellNum">
      <a-input-number
        v-model:value="form.cellNum"
        class="formInput"
        :controls="false"
      />
    </a-form-item>
    <!-- <div class="blockConfig">
      <a-button type="link" @click="handleBlockConfig" class="blockConfigBtn"
        >电池簇配置</a-button
      >
    </div> -->
    <a-form-item name="blockIdList" class="blockConfig">
      <a-button type="link" @click="handleBlockConfig" class="blockConfigBtn"
        >电池簇配置</a-button
      >
    </a-form-item>
    <!-- 隐藏的电池簇配置验证字段 -->
    <a-form-item name="blockIdList" style="display: none">
      <a-input v-model:value="form.blockIdList" />
    </a-form-item>
  </a-form>
  <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
    <a-button v-if="!configData?.isEdit" type="primary" @click="handleEdit"
      >编辑</a-button
    >
    <a-button
      v-else
      type="primary"
      @click="onSubmit"
      :loading="stionConfigState.configDataSaveLoading"
      >保存</a-button
    >
  </a-form-item>

  <!-- 电池簇配置弹窗 -->
  <a-modal
    v-model:open="blockConfigVisible"
    title="电池簇配置"
    class="addStation blockConfigModal"
    destroyOnClose
    :width="1000"
    @cancel="cancelBlockConfig"
    centered
  >
    <a-table
      :columns="blockConfigColumns"
      :data-source="blockConfigData"
      bordered
      :pagination="false"
      :scroll="{ x: 'max-content' }"
      class="blockConfigTable"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex === 'blockName'">
          <div>
            <a-input
              v-model:value="record.blockName"
              class="blockInput"
              placeholder="电池簇名称"
              allow-clear
            />
          </div>
        </template>
        <template v-if="column.dataIndex === 'blockIdx'">
          <div>
            <a-input
              v-model:value="record.blockIdx"
              class="blockInput"
              placeholder="电池簇唯一标识"
              allow-clear
            />
          </div>
        </template>
        <template v-if="column.dataIndex === 'orderNum'">
          <div>
            <a-input
              v-model:value="record.orderNum"
              class="blockInput"
              placeholder="资产设备编号"
              allow-clear
            />
          </div>
        </template>
        <template v-if="column.dataIndex === 'blockAsserCode'">
          <div>
            <a-input
              v-model:value="record.blockAsserCode"
              class="blockInput"
              placeholder="电池簇资产编码"
              allow-clear
            />
          </div>
        </template>
        <template v-if="column.dataIndex === 'handle'">
          <a-button
            v-if="!record.id"
            type="link"
            danger
            @click="delBlockData(index)"
            >删除</a-button
          >
        </template>
      </template>
    </a-table>
    <div class="addBtn" v-if="!(form.id && configData.isEdit)">
      <a-button type="link" @click="handleAddBlock"
        ><PlusOutlined />新增</a-button
      >
    </div>
    <template #footer>
      <div class="footerBar">
        <a-button key="back" @click="cancelBlockConfig">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="blockConfigLoading"
          @click="confirmBlockConfig"
          >确定</a-button
        >
      </div>
    </template>
  </a-modal>
</template>
<script setup>
import { EQUIP_TYPE } from "@/constants/stationConfig";
import { PlusOutlined } from "@ant-design/icons-vue";
const emits = defineEmits(["getConfig"]);
import { useStionConfigStore } from "@/stores/stationConfig";
const { stionConfigState, changeConfigData } = useStionConfigStore();
const configData = computed(() => stionConfigState.configData);
import { cloneDeep } from "lodash-es";
const props = defineProps({
  rowData: {
    type: Object,
  },
  elements: {
    type: Array,
  },
});
watch(
  () => stionConfigState.configData,
  (val) => {
    handleInit();
  },
  { deep: true }
);
const BIAN_YA_QI_LIST = computed(() =>
  props.elements.filter((item) => item.type === EQUIP_TYPE.BIAN_YA_QI)
);
const $api = inject("$api");
const form = ref({
  supplierId: null,
  typeId: null,
  linkAssetCode: null,
  linkName: null,
  orderNum: null,
  isMain: 0,
  belongId: null,
  linkIdx: null,
  blockNum: null,
  packNum: null,
  cellNum: null,
  tfId: null,
  type: EQUIP_TYPE.JI_ZHUANG_XIANG,
  blockIdList: [], // 电池簇配置数据
});
const formRef = ref();
const rules = {
  supplierId: [{ required: true, message: "请选择", trigger: "change" }],
  typeId: [{ required: true, message: "请选择", trigger: "change" }],
  linkName: [{ required: true, message: "请输入", trigger: "change" }],
  linkAssetCode: [{ required: true, message: "请输入", trigger: "change" }],
  isMain: [{ required: true, message: "请选择", trigger: "change" }],
  belongId: [{ required: true, message: "请选择", trigger: "change" }],
  linkIdx: [{ required: true, message: "请输入", trigger: "change" }],
  blockNum: [{ required: true, message: "请输入", trigger: "change" }],
  packNum: [{ required: true, message: "请输入", trigger: "change" }],
  cellNum: [{ required: true, message: "请输入", trigger: "change" }],
  tfId: [{ required: true, message: "请选择", trigger: "change" }],
  blockIdList: [
    {
      validator: (rule, value) => {
        return new Promise((resolve, reject) => {
          // 如果没有设置电池簇数量，则不需要验证
          if (!form.value.blockNum || form.value.blockNum === 0) {
            resolve();
            return;
          }

          // 如果没有电池簇配置数据，则验证失败
          if (!value || value.length === 0) {
            reject(new Error("请完成电池簇配置"));
            return;
          }
          // 验证电池簇配置行数与设置的数量是否一致
          if (value.length !== form.value.blockNum) {
            reject(new Error("请完善电池簇配置"));
            return;
          }
          // 使用已有的验证函数验证电池簇配置数据
          const errors = validateBlockConfigData(value);
          if (errors.length > 0) {
            reject(new Error(errors[0]));
            return;
          }

          resolve();
        });
      },
      trigger: "change",
    },
  ],
};
// 电池簇配置相关状态
const blockConfigVisible = ref(false);
const blockConfigLoading = ref(false);
const blockConfigData = ref([]);
// 电池簇配置表格列定义
const blockConfigColumns = computed(() => {
  const baseColumns = [
    {
      title: () =>
        h("span", [h("span", { style: { color: "red" } }, "*"), "电池簇名称"]),
      dataIndex: "blockName",
      key: "blockName",
    },
    {
      title: () =>
        h("span", [
          h("span", { style: { color: "red" } }, "*"),
          "电池簇唯一标识",
        ]),
      dataIndex: "blockIdx",
      key: "blockIdx",
    },
    {
      title: () =>
        h("span", [
          h("span", { style: { color: "red" } }, "*"),
          "资产设备编号",
        ]),
      dataIndex: "orderNum",
      key: "orderNum",
    },
    {
      title: "电池簇资产编码",
      dataIndex: "blockAsserCode",
      key: "blockAsserCode",
    },
  ];

  // 判断是否为编辑状态（非新增），如果是编辑状态且有id，则不显示操作列
  const isEdit = form.value.id && configData.value.isEdit;
  if (!isEdit) {
    baseColumns.push({
      title: "操作",
      dataIndex: "handle",
      key: "handle",
      width: 60,
      fixed: "right",
    });
  }

  return baseColumns;
});
// 处理电池簇配置按钮点击
const handleBlockConfig = () => {
  blockConfigVisible.value = true;
  initBlockConfigData();
};
const supplierList = ref([]);
const supplierTypeList = ref([]);
const getSupplierTypeTree = async () => {
  const res = await $api.supplierTypeTree();
  supplierList.value = res.data;
};
const handleSupplierTypeList = (id) => {
  supplierTypeList.value =
    supplierList.value.filter((item) => item.supplierId === id)[0]
      ?.supplierTypeEntities || [];
};
const energyLinkList = ref([]);
const getEnergyLinkPage = async () => {
  // 获取电池堆列表 如果不是主电池堆，需要拉取电池堆列表指定所属
  const res = await $api.energyLinkList({
    stationId: props.rowData.stationId,
  });
  energyLinkList.value = res?.data;
};
// 初始化电池簇配置数据
const initBlockConfigData = () => {
  blockConfigData.value = [];
  // 确定目标行数
  const targetCount = form.value.blockNum || 1;
  if (form.value.blockIdList && form.value.blockIdList.length > 0) {
    blockConfigData.value = cloneDeep(form.value.blockIdList);
  }
  // 调整行数与电池簇数量一致
  if (blockConfigData.value.length < targetCount) {
    // 如果配置行数少于目标数量，补充行数
    for (let i = blockConfigData.value.length + 1; i <= targetCount; i++) {
      blockConfigData.value.push({
        id: i,
        blockName: `${i}`,
        blockIdx: "",
        orderNum: "",
        blockAsserCode: "",
      });
    }
  } else if (blockConfigData.value.length > targetCount) {
    // 如果配置行数多于目标数量，删减多余行数
    blockConfigData.value = blockConfigData.value.slice(0, targetCount);
  }
  blockConfigData.value.forEach((item, index) => {
    item.id = index + 1;
  });
};

// 新增电池簇行
const handleAddBlock = () => {
  const newId = blockConfigData.value.length + 1;
  blockConfigData.value.push({
    // id: newId,
    blockName: `${newId}`,
    blockIdx: "",
    orderNum: "",
    blockAsserCode: "",
  });
};

// 删除电池簇行
const delBlockData = (index) => {
  if (blockConfigData.value.length <= 1) {
    message.warning("至少保留一行数据");
    return;
  }
  blockConfigData.value.splice(index, 1);
  // 重新编号
  blockConfigData.value.forEach((item, idx) => {
    item.id = idx + 1;
  });
};

// 验证电池簇配置数据
const validateBlockConfigData = (dataSource) => {
  const errors = [];
  // 如果传入了数据源，使用传入的数据源，否则使用 blockConfigData 或 form.value.blockIdList
  const dataToValidate =
    dataSource || blockConfigData.value || form.value.blockIdList || [];

  dataToValidate.forEach((item, index) => {
    const rowNum = index + 1;
    if (!item.blockName || item.blockName.trim() === "") {
      errors.push(`第${rowNum}行：电池簇名称不能为空`);
    }
    if (!item.blockIdx || item.blockIdx.trim() === "") {
      errors.push(`第${rowNum}行：电池簇唯一标识不能为空`);
    }
    if (!item.orderNum || item.orderNum.trim() === "") {
      errors.push(`第${rowNum}行：资产设备编号不能为空`);
    }
  });

  return errors;
};

// 确认电池簇配置
const confirmBlockConfig = () => {
  if (blockConfigData.value.length === 0) {
    message.warning("请至少添加一行电池簇配置");
    return;
  }
  // 校验配置的行数和外面的电池簇数量一致
  if (
    form.value.blockNum &&
    blockConfigData.value.length !== form.value.blockNum
  ) {
    message.error(`电池簇配置行数与设置的电池簇数量不一致，请保持一致`);
    return;
  }
  const errors = validateBlockConfigData();
  if (errors.length > 0) {
    message.error(errors[0]);
    return;
  }
  blockConfigLoading.value = true;
  form.value.blockIdList = cloneDeep(blockConfigData.value);

  // 触发表单验证，更新 blockIdList 字段的验证状态
  nextTick(() => {
    formRef.value?.validateFields(["blockIdList"]);
  });

  blockConfigVisible.value = false;
  blockConfigLoading.value = false;
};
// 取消电池簇配置
const cancelBlockConfig = () => {
  blockConfigVisible.value = false;
};
const onSubmit = async () => {
  try {
    await formRef.value.validate();
    form.value.type = EQUIP_TYPE.JI_ZHUANG_XIANG;
    // 注意：拉取blockid的containerRelation逻辑，在父组件getConfig中处理
    emits("getConfig", toRaw(form));
  } catch (error) {
    console.log("表单验证失败:", error);
  }
};
const labelCol = { style: { width: "150px" } };
const wrapperCol = { span: 14 };
const handleEdit = () => {
  changeConfigData({
    ...stionConfigState.configData,
    isEdit: true,
  });
};
const changeSupplierType = (id) => {
  form.value.typeId = null;
  handleSupplierTypeList(id);
};
const handleInit = async () => {
  form.value = cloneDeep(stionConfigState.configData);
  form.value.supplierId = props.rowData.supplierId;
  form.value.typeId = props.rowData.typeId;
  handleSupplierTypeList(form.value.supplierId);
  if (form.value.supplierId && form.value.typeId) {
    changeType();
  }
};
const changeType = async () => {
  if (form.value.packNum || form.value.cellNum) {
    return;
  }
  // 没packNum和cellNum再进行默认值拉取处理
  const params = {
    supplierId: form.value.supplierId,
    typeId: form.value.typeId,
    businessType: 0,
    current: 1,
    size: 10,
  };
  const res = await $api.supplierTypePage(params);
  if (res.code === 0 && res?.data?.records.length) {
    form.value.packNum = res.data.records[0].packNumberPerCluster;
    form.value.cellNum = res.data.records[0].cellNumberPerPack;
  }
};
onMounted(async () => {
  await getSupplierTypeTree();
  await getEnergyLinkPage();
});
</script>
<style lang="less" scoped>
.formInput,
.formSelect {
  width: 175px;
  text-align: left;
}
.blockConfig {
  position: relative;
  bottom: 10px;
  :deep(.ant-form-item-explain-error) {
    width: 150px;
    padding-left: 0px !important;
  }
}
.blockConfigBtn {
  padding: 0;
  width: 150px;
  text-align: left;
}

.blockConfigModal {
  .blockConfigTable {
    margin-top: 16px;
  }

  .blockInput {
    width: 100%;
    min-width: 150px;
  }

  .addBtn {
    text-align: right;
    margin: 16px 0;

    .btn {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      padding: 8px 16px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      color: #1890ff;
      background: #fafafa;
      transition: all 0.3s;

      &:hover {
        border-color: #1890ff;
        background: #f0f8ff;
      }
    }
  }

  .footerBar {
    display: flex;
    justify-content: center;
    gap: 8px;
  }
}
</style>
